<?php

/**
 * @Author: Ron Chen
 * @Date:   2017-10-29 20:05:28
 * @Last Modified by:   Ron Chen
 * @Last Modified time: 2017-10-29 20:06:22
 */
namespace common\helpers;
use Yii;

class GlobalHelper
{
	public static function getDomain()
	{
		$domain = isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : $_SERVER['SERVER_NAME'];
		
		return $domain;
	}

    /**
     * ping db 数据库操作
     * @param string $db
     * @return \yii\db\Connection
     */
    public static function pingDb($db = 'db'){
        $db_handle  = Yii::$app->$db;
        $db_handle->createCommand("select 1")->queryOne();
    }

    /**
     * connect db 重新连接数据库
     * @param string $db
     * @return \yii\db\Connection 返回数据库操作句柄
     */
    public static function connectDb($db = 'db'){
        $db_handle  = Yii::$app->$db;
        if(empty($db_handle)) {
            return false;
        }

        try{
            $db_handle->createCommand("select 1")->queryOne();
        }catch (\Exception $e){
            $db_handle->close();
            $db_handle->open();
        }
    }
    /**
     * connect redis 重新连接数据库
     * @param string|[] $redis
     */
    public static function connectRedis($redis = 'redis'){
        $redises = is_array($redis) ? $redis : [$redis];
        foreach($redises as $v){
            $redis_handle  = Yii::$app->$v;
            if(empty($redis_handle)) {
                continue;
            }
            try{
                if(!$redis_handle->ping()){
                    throw new \Exception('redis connection closed');
                }
            }catch (\Exception $e){
                Yii::$app->set($v,\Yii::$app->components[$v]);
            }
        }
    }
}